# PyMSQL创建数据库连接
from pymysql import Connection

conn = None
try:
    # 创建数据库连接
    conn = Connection(
        host='localhost',  # 主机地址
        port=3306,  # 端口
        user='root',  # 用户名
        password='root',  # 密码
        database='learn_pymysql'  # 数据库
    )
    # 获取游标
    cursor = conn.cursor()

    # 定义一个建表sql语句
    sql = '''
        CREATE TABLE `regions` (
          `region_id` int(11) NOT NULL,
          `region_name` varchar(25) DEFAULT NULL,
          PRIMARY KEY (`region_id`),
          UNIQUE KEY `reg_id_pk` (`region_id`)
        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    '''

    # 选择要操作的数据库
    # conn.select_db("learn_pymysql")  # 可在connection中配置

    # 使用游标对象执行sql
    cursor.execute(sql)

except Exception as e:
    print("发生异常：", e)
finally:
    if conn:
        # 关闭连接
        conn.close()
